"""
消息相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from app.services import MessageService

# 创建蓝图
message_bp = Blueprint('message', __name__, url_prefix='/message')

@message_bp.route('/')
@login_required
def message_center():
    """消息中心首页"""
    page = request.args.get('page', 1, type=int)
    per_page = 10
    unread_only = request.args.get('unread_only', 'false').lower() == 'true'
    
    # 获取用户消息列表
    messages = MessageService.get_user_messages(
        user_id=current_user.id,
        page=page,
        per_page=per_page,
        unread_only=unread_only
    )
    
    # 获取未读消息数量
    unread_count = MessageService.get_unread_count(current_user.id)
    
    return render_template('message/message_center.html', 
                          messages=messages,
                          unread_count=unread_count,
                          unread_only=unread_only)

@message_bp.route('/<int:message_id>')
@login_required
def view_message(message_id):
    """查看消息详情"""
    # 标记消息为已读
    success = MessageService.mark_message_as_read(current_user.id, message_id)
    
    if not success:
        flash('消息不存在或无权限查看')
        return redirect(url_for('message.message_center'))
    
    # 获取消息详情
    from app.models import Message, MessageRecipient, get_db
    db = get_db()
    
    # 先尝试获取直接发送给用户的消息
    message = Message.query.filter_by(id=message_id, receiver_id=current_user.id).first()
    
    # 如果不是直接发送的消息，尝试获取群发给用户的消息
    if not message:
        recipient = MessageRecipient.query.filter_by(
            message_id=message_id, 
            user_id=current_user.id
        ).first()
        if recipient:
            message = recipient.message
    
    if not message:
        flash('消息不存在或无权限查看')
        return redirect(url_for('message.message_center'))
    
    # 获取发送者信息
    sender = message.sender
    
    return render_template('message/message_detail.html', 
                          message=message,
                          sender=sender)

@message_bp.route('/mark_read/<int:message_id>', methods=['POST'])
@login_required
def mark_as_read(message_id):
    """标记消息为已读"""
    success = MessageService.mark_message_as_read(current_user.id, message_id)
    
    if success:
        return jsonify({'success': True, 'message': '消息已标记为已读'})
    else:
        return jsonify({'success': False, 'message': '操作失败'}), 400

@message_bp.route('/mark_all_read', methods=['POST'])
@login_required
def mark_all_as_read():
    """标记所有消息为已读"""
    success = MessageService.mark_all_as_read(current_user.id)
    
    if success:
        return jsonify({'success': True, 'message': '所有消息已标记为已读'})
    else:
        return jsonify({'success': False, 'message': '操作失败'}), 400

@message_bp.route('/unread_count')
@login_required
def get_unread_count():
    """获取未读消息数量"""
    count = MessageService.get_unread_count(current_user.id)
    return jsonify({'count': count})

@message_bp.route('/compose', methods=['GET', 'POST'])
@login_required
def compose_message():
    """撰写消息"""
    if request.method == 'POST':
        title = request.form.get('title')
        content = request.form.get('content')
        message_type = request.form.get('message_type', '系统通知')
        priority = request.form.get('priority', '普通')
        recipient_ids = request.form.getlist('recipient_ids')
        
        if not title or not content:
            flash('标题和内容不能为空')
            return redirect(url_for('message.compose_message'))
        
        # 如果没有选择接收者，发送给所有管理员
        if not recipient_ids:
            recipient_ids = MessageService.get_admins_and_sales_leads()
        
        # 如果只有一个接收者，使用单条消息
        if len(recipient_ids) == 1:
            MessageService.create_message(
                title=title,
                content=content,
                message_type=message_type,
                sender_id=current_user.id,
                recipient_id=recipient_ids[0],
                priority=priority
            )
        else:
            # 否则使用批量消息
            MessageService.create_bulk_message(
                title=title,
                content=content,
                message_type=message_type,
                sender_id=current_user.id,
                recipient_ids=recipient_ids,
                priority=priority
            )
        
        flash('消息发送成功')
        return redirect(url_for('message.message_center'))
    
    # 获取所有用户，用于选择接收者
    from app.models import User
    users = User.query.filter_by(is_active=True).all()
    
    return render_template('message/compose_message.html', users=users)

@message_bp.route('/api/mark-read/<int:message_id>', methods=['POST'])
@login_required
def api_mark_as_read(message_id):
    """标记消息为已读（API接口）"""
    success = MessageService.mark_message_as_read(current_user.id, message_id)
    
    if success:
        return jsonify({'success': True, 'message': '消息已标记为已读'})
    else:
        return jsonify({'success': False, 'message': '操作失败'}), 400

@message_bp.route('/api/<int:message_id>/recipients')
@login_required
def get_message_recipients(message_id):
    """获取消息的接收者列表"""
    # 只有管理员可以查看消息接收者列表
    if current_user.role != 'admin':
        return jsonify({'success': False, 'message': '无权限访问'}), 403
    
    from app.models import Message, MessageRecipient, get_db
    db = get_db()
    
    # 获取消息
    message = Message.query.get_or_404(message_id)
    
    recipients = []
    
    # 如果是单条消息，直接返回接收者
    if message.receiver_id:
        user = message.recipient
        if user:
            recipients.append({
                'id': user.id,
                'name': user.name,
                'read': message.is_read
            })
    # 如果是群发消息，获取所有接收者
    else:
        message_recipients = MessageRecipient.query.filter_by(message_id=message_id).all()
        for mr in message_recipients:
            user = mr.user
            if user:
                recipients.append({
                    'id': user.id,
                    'name': user.name,
                    'read': mr.is_read
                })
    
    return jsonify({
        'success': True,
        'recipients': recipients
    })

@message_bp.route('/api/<int:message_id>/detail')
@login_required
def get_message_detail(message_id):
    """获取消息详情（API接口，用于弹窗显示）"""
    from app.models import Message, MessageRecipient, get_db
    db = get_db()
    
    # 系统管理员可以查看所有消息
    if current_user.role == 'admin':
        message = Message.query.get_or_404(message_id)
    else:
        # 普通用户只能查看发给自己的消息
        # 先尝试获取直接发送给用户的消息
        message = Message.query.filter_by(id=message_id, receiver_id=current_user.id).first()
        
        # 如果不是直接发送的消息，尝试获取群发给用户的消息
        if not message:
            recipient = MessageRecipient.query.filter_by(
                message_id=message_id, 
                user_id=current_user.id
            ).first()
            if recipient:
                message = recipient.message
    
    if not message:
        return jsonify({'success': False, 'message': '消息不存在或无权限查看'}), 404
    
    # 获取发送者信息
    sender = message.sender
    
    # 获取接收者列表（仅管理员可见）
    recipients = []
    if current_user.role == 'admin':
        # 如果是单条消息，直接返回接收者
        if message.receiver_id:
            user = message.recipient
            if user:
                recipients.append({
                    'id': user.id,
                    'name': user.name,
                    'read': message.is_read
                })
        # 如果是群发消息，获取所有接收者
        else:
            message_recipients = MessageRecipient.query.filter_by(message_id=message_id).all()
            for mr in message_recipients:
                user = mr.user
                if user:
                    recipients.append({
                        'id': user.id,
                        'name': user.name,
                        'read': mr.is_read
                    })
    
    return jsonify({
        'success': True,
        'message': {
            'id': message.id,
            'title': message.title,
            'content': message.content,
            'message_type': message.message_type,
            'priority': message.priority,
            'is_read': message.is_read,
            'created_at': message.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'sender': {
                'id': sender.id if sender else None,
                'name': sender.name if sender else '系统'
            },
            'target_type': message.target_type,
            'target_id': message.target_id,
            'recipients': recipients
        }
    })

@message_bp.route('/system/list')
@login_required
def system_message_list():
    """系统管理-消息列表"""
    # 只有管理员可以访问系统消息列表
    if current_user.role != 'admin':
        flash('无权限访问此页面')
        return redirect(url_for('main.home'))
    
    page = request.args.get('page', 1, type=int)
    per_page = 20
    
    # 获取所有消息，按创建时间倒序
    from app.models import Message, get_db
    db = get_db()
    messages = Message.query.order_by(Message.created_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return render_template('admin/message_list.html', 
                          messages=messages,
                          current_menu='system',
                          current_page='system_message_list')

@message_bp.route('/templates')
@login_required
def message_templates():
    """消息模板管理"""
    # 只有管理员可以管理模板
    if current_user.role != 'admin':
        flash('无权限访问此页面')
        return redirect(url_for('message.message_center'))
    
    from app.models import MessageTemplate
    templates = MessageTemplate.query.all()
    
    return render_template('message/message_templates.html', templates=templates)

@message_bp.route('/template/create', methods=['GET', 'POST'])
@login_required
def create_template():
    """创建消息模板"""
    # 只有管理员可以创建模板
    if current_user.role != 'admin':
        flash('无权限访问此页面')
        return redirect(url_for('message.message_center'))
    
    if request.method == 'POST':
        name = request.form.get('name')
        title_template = request.form.get('title_template')
        content_template = request.form.get('content_template')
        message_type = request.form.get('message_type')
        priority = request.form.get('priority', '普通')
        
        if not name or not title_template or not content_template or not message_type:
            flash('所有字段都是必填的')
            return redirect(url_for('message.create_template'))
        
        from app.models import MessageTemplate
        # 检查名称是否已存在
        if MessageTemplate.query.filter_by(name=name).first():
            flash('模板名称已存在')
            return redirect(url_for('message.create_template'))
        
        template = MessageTemplate(
            name=name,
            title_template=title_template,
            content_template=content_template,
            message_type=message_type,
            priority=priority
        )
        
        from app.models import get_db
        db = get_db()
        db.session.add(template)
        db.session.commit()
        
        flash('模板创建成功')
        return redirect(url_for('message.message_templates'))
    
    return render_template('message/create_template.html')